package org.hot100_6.leetcode3;

import java.util.HashSet;

public class Solution3 {
    public static void main(String[] args) {
        String test  = "dvdf";
        int lengthOfLongestSubstring = lengthOfLongestSubstring2(test);
        System.out.println(lengthOfLongestSubstring);
    }

    public static int lengthOfLongestSubstring(String s) {
        HashSet<Character> hashSet = new HashSet<>();
        int maxLength = 0;
        for (int left = 0; left < s.length(); left++) {
            int right = left;
            while (right < s.length() && !hashSet.contains(s.charAt(right))) {
                hashSet.add(s.charAt(right));
                right++;
            }
            maxLength = Math.max(maxLength, hashSet.size());
            hashSet.clear();
        }

        return maxLength;
    }

    public static int lengthOfLongestSubstring2(String s){
        HashSet<Character> hashSet = new HashSet<>();
        int n = s.length();
        int result = 0;
        int right = 0;
        for (int left = 0; left < n; left++) {
            if (left>0){
                hashSet.remove(s.charAt(left-1));
            }
            while (right<n && !hashSet.contains(s.charAt(right))){
                hashSet.add(s.charAt(right));
                right++;
            }

            result = Math.max(result,hashSet.size());
        }

        return result;
    }
}
